from flask import Blueprint,jsonify,request
import json

bp_ziyuan =Blueprint('ziyuan',__name__)

from  utils.db import db1
from comm import get_data

@bp_ziyuan.route('/ziyuan')
def ziyuan():
    uid = request.args.get('uid')

    # sql = "select resource.name,resource.id from resource left join resource_user as u on u.resource_id = resource.id where users_id = %d" % int(uid)

    sql = "select * from resource"

    res = db1.find_all(sql)

    return jsonify({'code':200,'list':res})

@bp_ziyuan.route('/quanxian',methods=["POST"])
def quanxian():

    data = get_data()
    sql = "delete from resource_user where users_id  = %d"  % int(data['uid'])
    db1.update(sql)
    for i in json.loads(str(data['resource_id'])):
        sql = "insert into resource_user(resource_id,users_id) values(%d,%d)" % (int(i),int(data['uid']))
        db1.update(sql)
    return jsonify({'code':200,'mes':'添加成功'})







@bp_ziyuan.route('/getzi')
def getzi():
    uid = request.args.get('uid')
    sql = "select resource_id from resource_user where users_id = %d" % int(uid)

    res = db1.find_all(sql)

    return jsonify({'code':200,'list':res})


# 获取全部资源
@bp_ziyuan.route('/ziyuanall')
def ziyuanall():
    # sql1 = " select r.name from resource  as r  left join resource_user as ur on r.id=ur.resource_id where ur.users_id is NULL and r.type=1;"

    sql = "select * from resource"

    res1 = db1.find_all(sql)

    return jsonify({'code':200,'list':res1})





@bp_ziyuan.route('/getrole')
def getrole():
    sql = "select * from role"

    res = db1.find_all(sql)

    return jsonify({'code':200,'list':res})


@bp_ziyuan.route('/addrole',methods=["POST"])
def addrole():

    data = get_data()

    # 查询出用户所拥有的资源
    sql = "select * from role_resource as ro left join role on role.id = ro.role_id where id = %d " % int(data['uid'])

    res = db1.find_all(sql)

    sql1 = "delete from role_resource where role_id = %d" % int(data['role_id'])

    db1.update(sql1)


    for i in json.loads(str(data['resource_id'])):
        sql2 = "insert into role_resource(role_id,resource_id) values(%d,%d)" int(data['role_id']),int(data['resource_id'])

        db1.find_all(sql2)
        return jsonify({'code':200,'mes':'成功'})












# 用户配置角色





